﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcFlow.Mvc.ActionResults
{
    [Serializable]
    public class ViewActionResult : IActionResult 
    {
        private readonly Dictionary<string,object> viewData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); 

        public bool                         IsPartialView   { get; set; }

        public string                       ViewName        { get; set; }
        public string                       LayoutName      { get; set; }

        public IDictionary<string,object>   ViewData        
        {
            get { return viewData; }
        }

        public object                       Model           { get; set; }

        public ActionResult Bind(ControllerBase controllerBase)
        {
            controllerBase.ViewData.Model = Model;

            foreach( var kv in viewData)
            {
                controllerBase.ViewData[kv.Key] = kv.Value;
            }

            if ( IsPartialView )
            {
                var viewResult = new ViewResult()
                {
                    ViewName    = ViewName,
                    TempData    = controllerBase.TempData,
                    ViewData    = controllerBase.ViewData,
                    MasterName  = LayoutName,
                };

                return viewResult;
            }

            var partialViewResult = new PartialViewResult()
            {
                ViewName = ViewName,
                TempData = controllerBase.TempData,
                ViewData = controllerBase.ViewData,
            };

            return partialViewResult;
        }
    }
}